package cn.itcast.www.junitTest;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class PrintLetters {

	private static Semaphore semaphoresA = new Semaphore(1);
	private static Semaphore semaphoresB = new Semaphore(0);
	private static Semaphore semaphoresC = new Semaphore(0);

	public static void main(String[] args) {
		
		ExecutorService service = Executors.newFixedThreadPool(3);

		service.execute(new PrintLetters.Print(PrintLetters.semaphoresA,PrintLetters.semaphoresB,'A'));
		service.execute(new PrintLetters.Print(PrintLetters.semaphoresB,PrintLetters.semaphoresC,'B'));
		service.execute(new PrintLetters.Print(PrintLetters.semaphoresC,PrintLetters.semaphoresA,'C'));

		service.shutdown();
	}

	private static class Print implements Runnable {
		private Semaphore semaphore1;
		private Semaphore semaphore2;
		private char letter;
		public Print(Semaphore semaphore1, Semaphore semaphore2, char letter) {
			this.semaphore1 = semaphore1;
			this.semaphore2 = semaphore2;
			this.letter = letter;
		}
		
		public void run() {

			for (int i = 0; i < 10; i++) {
				try {
					semaphore1.acquire();
				} catch (InterruptedException e) {					
					e.printStackTrace();
				}
				System.out.println(String.format("第%d遍", i + 1));
				System.out.println(letter);
				semaphore2.release();

			}
		}
	}
}